package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxAdmin;
import com.adk.backend.entity.LxAdminGroup;
import com.adk.backend.service.AdminService;
import com.adk.backend.service.PermissionService;
import com.adk.backend.service.CustomerService;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private LogUtil logUtil;
    
    @Autowired
    private com.adk.backend.service.OrderStatusService orderStatusService;
    
    /**
     * 分页查询管理员列表
     */
    @RequiresPermission("list")
    @GetMapping("/list")
    public Result<PageResult<LxAdmin>> getAdminList(
            @RequestParam(required = false) Integer gid,
            @RequestParam(required = false) Integer cid,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("gid", gid);
            params.put("cid", cid);
            params.put("status", status);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<LxAdmin> result = adminService.getAdminList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取管理员列表失败", e);
            return Result.error("获取管理员列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取管理员详情
     */
    @RequiresPermission("list")
    @GetMapping("/detail")
    public Result<LxAdmin> getAdminDetail(@RequestParam Long id) {
        try {
            LxAdmin admin = adminService.getById(id);
            if (admin != null) {
                // 不返回密码
                admin.setAdminpwd("");
                return Result.success(admin);
            }
            return Result.error("管理员不存在");
        } catch (Exception e) {
            log.error("获取管理员详情失败", e);
            return Result.error("获取管理员详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建管理员
     */
    @RequiresPermission("add")
    @PostMapping("/create")
    public Result<LxAdmin> createAdmin(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            LxAdmin admin = new LxAdmin();
            admin.setUsername((String) request.get("username"));
            admin.setMobi((String) request.get("mobi"));
            admin.setEmail((String) request.get("email"));
            admin.setUserType((Integer) request.get("userType"));
            
            // 客户ID（当user_type=13时）
            if (request.get("customerId") != null) {
                admin.setCustomerId(((Number) request.get("customerId")).longValue());
            }
            
            // 业务类型（当user_type=4时）
            if (request.get("ywType") != null) {
                admin.setYwType((Integer) request.get("ywType"));
            }
            
            // 仓库ID（当user_type=9或45时）
            if (request.get("whId") != null) {
                admin.setWhId(((Number) request.get("whId")).longValue());
            }
            
            String password = (String) request.get("password");
            
            LxAdmin result = adminService.createAdmin(admin, password);
            
            // 记录操作日志
            Long userId = (Long) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            if (userId != null && username != null) {
                logUtil.logAction(userId, username, "admin", result.getId(), "新建了管理员账号" + result.getEmail(), httpRequest);
            }
            
            // 不返回密码
            result.setAdminpwd("");
            return Result.success("创建成功", result);
        } catch (Exception e) {
            log.error("创建管理员失败", e);
            return Result.error("创建管理员失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新管理员
     */
    @RequiresPermission("edit")
    @PostMapping("/update")
    public Result<Boolean> updateAdmin(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            LxAdmin admin = new LxAdmin();
            admin.setId(((Number) request.get("id")).longValue());
            admin.setUsername((String) request.get("username"));
            admin.setMobi((String) request.get("mobi"));
            admin.setEmail((String) request.get("email"));
            admin.setUserType((Integer) request.get("userType"));
            
            // 客户ID（当user_type=13时）
            if (request.get("customerId") != null) {
                admin.setCustomerId(((Number) request.get("customerId")).longValue());
            }
            
            // 业务类型（当user_type=4时）
            if (request.get("ywType") != null) {
                admin.setYwType((Integer) request.get("ywType"));
            }
            
            // 仓库ID（当user_type=9或45时）
            if (request.get("whId") != null) {
                admin.setWhId(((Number) request.get("whId")).longValue());
            }
            
            String password = (String) request.get("password");
            if (password != null && password.isEmpty()) {
                password = null;
            }
            
            boolean success = adminService.updateAdmin(admin, password);
            
            if (success) {
                // 记录操作日志
                Long userId = (Long) httpRequest.getAttribute("userId");
                String username = (String) httpRequest.getAttribute("username");
                if (userId != null && username != null) {
                    logUtil.logAction(userId, username, "admin", admin.getId(), "更新了管理员账号" + admin.getEmail(), httpRequest);
                }
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新管理员失败", e);
            return Result.error("更新管理员失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除管理员
     */
    @RequiresPermission("del")
    @PostMapping("/delete")
    public Result<Boolean> deleteAdmin(@RequestParam Long id, HttpServletRequest request) {
        try {
            LxAdmin admin = adminService.getById(id);
            boolean success = adminService.deleteAdmin(id);
            if (success) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null && admin != null) {
                    logUtil.logAction(userId, username, "admin", id, "删除了管理员账号" + admin.getEmail(), request);
                }
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除管理员失败", e);
            return Result.error("删除管理员失败：" + e.getMessage());
        }
    }
    
    /**
     * 切换管理员状态
     */
    @RequiresPermission("edit")
    @PostMapping("/toggle-status")
    public Result<Boolean> toggleStatus(@RequestParam Long id, HttpServletRequest request) {
        try {
            LxAdmin admin = adminService.getById(id);
            boolean success = adminService.toggleStatus(id);
            if (success) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null && admin != null) {
                    String action = admin.getStatus() == 0 ? "启用了管理员账号" : "禁用了管理员账号";
                    logUtil.logAction(userId, username, "admin", id, action + admin.getEmail(), request);
                }
                return Result.success("操作成功", true);
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            log.error("切换管理员状态失败", e);
            return Result.error("切换管理员状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 强制退出（清除Token）
     */
    @RequiresPermission("edit")
    @PostMapping("/logout")
    public Result<Boolean> logout(@RequestParam Long id, HttpServletRequest request) {
        try {
            boolean success = adminService.logout(id);
            if (success) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    logUtil.logAction(userId, username, "admin", id, "强制退出了管理员账号", request);
                }
                return Result.success("操作成功", true);
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            log.error("强制退出失败", e);
            return Result.error("强制退出失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户组列表
     */
    @RequiresPermission("list")
    @GetMapping("/groups")
    public Result<java.util.List<LxAdminGroup>> getAdminGroups() {
        try {
            java.util.List<LxAdminGroup> groups = permissionService.getAllGroups();
            return Result.success(groups);
        } catch (Exception e) {
            log.error("获取用户组列表失败", e);
            return Result.error("获取用户组列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取页面数据（用户组列表、客户列表等）
     */
    @RequiresPermission("list")
    @GetMapping("/page-data")
    public Result<Map<String, Object>> getPageData(@RequestParam(required = false) Integer gid) {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 获取用户组列表
            java.util.List<LxAdminGroup> groups = permissionService.getAllGroups();
            data.put("groups", groups);
            
            // 如果是客户用户组（gid=13），获取客户列表
            if (gid != null && gid == 13) {
                data.put("customers", customerService.getAllEnabledCustomers());
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取页面数据失败", e);
            return Result.error("获取页面数据失败：" + e.getMessage());
        }
    }
    
    // ==================== 用户组管理 ====================
    
    /**
     * 获取用户组列表
     */
    @RequiresPermission("list")
    @GetMapping("/groups/list")
    public Result<java.util.List<LxAdminGroup>> getGroupList() {
        try {
            java.util.List<LxAdminGroup> groups = permissionService.getAllGroups();
            return Result.success(groups);
        } catch (Exception e) {
            log.error("获取用户组列表失败", e);
            return Result.error("获取用户组列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户组详情（包含权限配置）
     */
    @RequiresPermission("list")
    @GetMapping("/groups/detail")
    public Result<Map<String, Object>> getGroupDetail(@RequestParam Integer id) {
        try {
            LxAdminGroup group = permissionService.getGroupById(id);
            if (group == null) {
                return Result.error("用户组不存在");
            }
            
            // 获取所有菜单和权限
            java.util.List<com.adk.backend.entity.LxAdminFile> files = permissionService.getAllFiles();
            java.util.List<com.adk.backend.entity.LxAdminFlag> allFlags = permissionService.getAllFlags();
            
            // 构建文件树（每个文件包含其下的权限）
            java.util.List<Map<String, Object>> fileTree = new java.util.ArrayList<>();
            for (com.adk.backend.entity.LxAdminFile file : files) {
                Map<String, Object> fileMap = new HashMap<>();
                fileMap.put("id", file.getId());
                fileMap.put("fileName", file.getFileName());
                fileMap.put("fileCn", file.getFileCn());
                fileMap.put("file", file.getFile());
                
                // 获取该文件下的权限列表
                java.util.List<com.adk.backend.entity.LxAdminFlag> fileFlags = new java.util.ArrayList<>();
                for (com.adk.backend.entity.LxAdminFlag flag : allFlags) {
                    if (flag.getFileId() != null && flag.getFileId().equals(file.getId())) {
                        fileFlags.add(flag);
                    }
                }
                fileMap.put("flags", fileFlags);
                fileTree.add(fileMap);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("group", group);
            result.put("fileTree", fileTree);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户组详情失败", e);
            return Result.error("获取用户组详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建或更新用户组
     */
    @RequiresPermission("edit")
    @PostMapping("/groups/save")
    public Result<Boolean> saveGroup(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Integer id = request.get("id") != null ? ((Number) request.get("id")).intValue() : null;
            String groupName = (String) request.get("groupName");
            String groupIntro = (String) request.get("groupIntro");
            
            // 获取选中的文件ID和权限ID
            java.util.List<Integer> allowFile = new java.util.ArrayList<>();
            java.util.List<Integer> allowFlag = new java.util.ArrayList<>();
            if (request.get("allowFile") != null) {
                @SuppressWarnings("unchecked")
                java.util.List<Object> allowFileObj = (java.util.List<Object>) request.get("allowFile");
                for (Object obj : allowFileObj) {
                    if (obj instanceof Number) {
                        allowFile.add(((Number) obj).intValue());
                    }
                }
            }
            if (request.get("allowFlag") != null) {
                @SuppressWarnings("unchecked")
                java.util.List<Object> allowFlagObj = (java.util.List<Object>) request.get("allowFlag");
                for (Object obj : allowFlagObj) {
                    if (obj instanceof Number) {
                        allowFlag.add(((Number) obj).intValue());
                    }
                }
            }
            
            LxAdminGroup group = new LxAdminGroup();
            if (id != null && id > 0) {
                group = permissionService.getGroupById(id);
                if (group == null) {
                    return Result.error("用户组不存在");
                }
            }
            
            if (groupName != null) {
                group.setGroupName(groupName);
            }
            if (groupIntro != null) {
                group.setGroupIntro(groupIntro);
            }
            
            // 将列表转换为逗号分隔的字符串
            if (allowFile != null && !allowFile.isEmpty()) {
                group.setAllowFile(String.join(",", allowFile.stream().map(String::valueOf).collect(java.util.stream.Collectors.toList())));
            } else {
                group.setAllowFile("");
            }
            
            if (allowFlag != null && !allowFlag.isEmpty()) {
                group.setAllowFlag(String.join(",", allowFlag.stream().map(String::valueOf).collect(java.util.stream.Collectors.toList())));
            } else {
                group.setAllowFlag("");
            }
            
            boolean success = permissionService.saveGroup(group);
            
            if (success) {
                // 记录操作日志
                Long userId = (Long) httpRequest.getAttribute("userId");
                String username = (String) httpRequest.getAttribute("username");
                if (userId != null && username != null) {
                    String action = id != null && id > 0 ? "更新了用户组" : "新建了用户组";
                    logUtil.logAction(userId, username, "admin_group", id != null ? id.longValue() : null, action + groupName, httpRequest);
                }
                return Result.success(id != null && id > 0 ? "更新成功" : "创建成功", true);
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            log.error("保存用户组失败", e);
            return Result.error("保存用户组失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除用户组
     */
    @RequiresPermission("del")
    @PostMapping("/groups/delete")
    public Result<Boolean> deleteGroup(@RequestParam Integer id, HttpServletRequest request) {
        try {
            // 不能删除id<=2的用户组
            if (id <= 2) {
                return Result.error("不能删除该用户组");
            }
            
            LxAdminGroup group = permissionService.getGroupById(id);
            boolean success = permissionService.deleteGroup(id);
            
            if (success) {
                // 将该用户组下的用户改为默认用户组（user_type=2），并禁用
                adminService.updateUserTypeToDefault(id);
                
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null && group != null) {
                    logUtil.logAction(userId, username, "admin_group", id.longValue(), "删除了用户组" + group.getGroupName(), request);
                }
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除用户组失败", e);
            return Result.error("删除用户组失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户组权限树（用于编辑）
     */
    @RequiresPermission("list")
    @GetMapping("/groups/permission-tree")
    public Result<Map<String, Object>> getPermissionTree(@RequestParam(required = false) Integer id) {
        try {
            // 获取所有菜单和权限
            java.util.List<com.adk.backend.entity.LxAdminFile> files = permissionService.getAllFiles();
            java.util.List<com.adk.backend.entity.LxAdminFlag> allFlags = permissionService.getAllFlags();
            
            // 获取当前用户组的权限（如果提供了id）
            java.util.Set<Integer> allowedFileIds = new java.util.HashSet<>();
            java.util.Set<Integer> allowedFlagIds = new java.util.HashSet<>();
            if (id != null && id > 0) {
                LxAdminGroup group = permissionService.getGroupById(id);
                if (group != null) {
                    if (group.getAllowFile() != null && !group.getAllowFile().isEmpty()) {
                        for (String fileId : group.getAllowFile().split(",")) {
                            if (!fileId.trim().isEmpty() && !"0".equals(fileId.trim())) {
                                allowedFileIds.add(Integer.parseInt(fileId.trim()));
                            }
                        }
                    }
                    if (group.getAllowFlag() != null && !group.getAllowFlag().isEmpty()) {
                        for (String flagId : group.getAllowFlag().split(",")) {
                            if (!flagId.trim().isEmpty() && !"0".equals(flagId.trim())) {
                                allowedFlagIds.add(Integer.parseInt(flagId.trim()));
                            }
                        }
                    }
                }
            }
            
            // 构建文件树
            java.util.List<Map<String, Object>> fileTree = new java.util.ArrayList<>();
            for (com.adk.backend.entity.LxAdminFile file : files) {
                Map<String, Object> fileMap = new HashMap<>();
                fileMap.put("id", file.getId());
                fileMap.put("fileName", file.getFileName());
                fileMap.put("fileCn", file.getFileCn());
                fileMap.put("file", file.getFile());
                fileMap.put("checked", allowedFileIds.contains(file.getId()));
                
                // 获取该文件下的权限列表
                java.util.List<Map<String, Object>> fileFlags = new java.util.ArrayList<>();
                for (com.adk.backend.entity.LxAdminFlag flag : allFlags) {
                    if (flag.getFileId() != null && flag.getFileId().equals(file.getId())) {
                        Map<String, Object> flagMap = new HashMap<>();
                        flagMap.put("id", flag.getId());
                        flagMap.put("flagAct", flag.getFlagAct());
                        flagMap.put("flagTitle", flag.getFlagTitle());
                        flagMap.put("checked", allowedFlagIds.contains(flag.getId()));
                        fileFlags.add(flagMap);
                    }
                }
                fileMap.put("flags", fileFlags);
                fileTree.add(fileMap);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("fileTree", fileTree);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取权限树失败", e);
            return Result.error("获取权限树失败：" + e.getMessage());
        }
    }
    
    // ==================== 客服管理 ====================
    
    /**
     * 获取客服管理列表（业务员列表，显示其所属客服）
     */
    @RequiresPermission("list")
    @GetMapping("/cs/list")
    public Result<java.util.List<Map<String, Object>>> getCsList() {
        try {
            java.util.List<Map<String, Object>> result = adminService.getSalesUsersWithCs();
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取客服管理列表失败", e);
            return Result.error("获取客服管理列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取业务员详情（用于设置客服）
     */
    @RequiresPermission("list")
    @GetMapping("/cs/detail")
    public Result<Map<String, Object>> getCsDetail(@RequestParam Long id) {
        try {
            Map<String, Object> result = adminService.getSalesUserDetail(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取业务员详情失败", e);
            return Result.error("获取业务员详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存业务员的客服配置
     */
    @RequiresPermission("edit")
    @PostMapping("/cs/save")
    public Result<Boolean> saveCs(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Long id = ((Number) request.get("id")).longValue();
            @SuppressWarnings("unchecked")
            java.util.List<Long> csIds = (java.util.List<Long>) request.get("csIds");
            
            boolean success = adminService.updateSalesUserCs(id, csIds);
            
            if (success) {
                // 记录操作日志
                Long userId = (Long) httpRequest.getAttribute("userId");
                String username = (String) httpRequest.getAttribute("username");
                if (userId != null && username != null) {
                    logUtil.logAction(userId, username, "admin", id, "修改了所属客服", httpRequest);
                }
                return Result.success("保存成功", true);
            }
            return Result.error("保存失败");
        } catch (Exception e) {
            log.error("保存客服配置失败", e);
            return Result.error("保存客服配置失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取客服列表（user_type=42）
     */
    @RequiresPermission("list")
    @GetMapping("/cs/cs-users")
    public Result<java.util.List<LxAdmin>> getCsUsers() {
        try {
            java.util.List<LxAdmin> csUsers = adminService.getCsUsers();
            return Result.success(csUsers);
        } catch (Exception e) {
            log.error("获取客服列表失败", e);
            return Result.error("获取客服列表失败：" + e.getMessage());
        }
    }
    
    // ==================== 微信设置 ====================
    
    /**
     * 获取微信设置
     */
    @RequiresPermission("list")
    @GetMapping("/wechat/settings")
    public Result<Map<String, Object>> getWechatSettings() {
        try {
            // 获取订单状态列表
            java.util.List<com.adk.backend.entity.LxOrderStatus> orderStatuses = orderStatusService.getAllStatusList();
            
            Map<String, Object> result = new HashMap<>();
            result.put("orderStatuses", orderStatuses);
            // TODO: 从数据库或配置文件读取微信设置
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取微信设置失败", e);
            return Result.error("获取微信设置失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存微信设置
     */
    @RequiresPermission("edit")
    @PostMapping("/wechat/save")
    public Result<Boolean> saveWechatSettings(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            // TODO: 保存微信设置到数据库或配置文件
            // Integer startA = (Integer) request.get("startA");
            // java.util.List<Integer> shipTypes = (Integer) request.get("shipTypes");
            // java.util.List<Integer> specTypes = (Integer) request.get("specTypes");
            // java.util.List<Integer> orderStatuses = (Integer) request.get("orderStatuses");
            
            // 记录操作日志
            Long userId = (Long) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            if (userId != null && username != null) {
                logUtil.logAction(userId, username, "wechat_settings", null, "更新了微信设置", httpRequest);
            }
            
            return Result.success("保存成功", true);
        } catch (Exception e) {
            log.error("保存微信设置失败", e);
            return Result.error("保存微信设置失败：" + e.getMessage());
        }
    }
}

